package com.gf.common.staticer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.gf.user.model.Suggestion;
import com.gf.user.model.User;
import com.gf.user.service.UserBaseService;
import com.gf.user.service.UserService;

/**
 * 单例<br>
 * 缓存所有的用户的昵称和对应的ID
 * 
 * @author zhuguifeng guifeng.net@gmail.com
 * @version 创建时间：2012-11-16 下午4:14:14
 */
@Component
public class AllNicknamesAndUID {

	private static AllNicknamesAndUID nicknameUid = new AllNicknamesAndUID();
	private static List<String> nicknames = new ArrayList<String>();// 用户的昵称
	private static List<String> uids = new ArrayList<String>();// 用户的ID
	private static Log logger = LogFactory.getLog(AllNicknamesAndUID.class);

	/**
	 * 记录当前最新的userId
	 */
	private static long lastUserId = 0;
	
	/**
	 * 当有新用户注册时，flag为true;
	 */
	public static boolean flag=false;

	@Autowired
	private UserService userService;

	@Autowired
	private UserBaseService userBaseService;

	private AllNicknamesAndUID() {

	}

	public static AllNicknamesAndUID getNicknameUid() {
		return nicknameUid;
	}

	/**
	 * 从数据库当到内存<br>
	 * 每10分钟更新一次
	 */
	@PostConstruct
	public void init() {
		logger.info("初始化 nickname uid");

		check();

		User user = userBaseService.getLatestUser();
		if (user != null) {
			lastUserId = user.getId();
		} else {
			lastUserId = 0;
		}
		logger.info("初始化 nickname uid 完成 lastUserId="+lastUserId);
	}

	private void check() {
		HashMap<String, List<String>> nicknameUidMap = userService
				.getAllNicknameAndUid();
		nicknames = nicknameUidMap.get("nickname");
		uids = nicknameUidMap.get("uid");
	}

	/**
	 * 每10分钟自动 更新
	 */
	public void updateNicknameUid() {
		if(flag){
			flag=false;
			User user = userBaseService.getLatestUser();
			// 有新用户注册
			if (user != null && user.getId() > lastUserId) {
				logger.info("nickname更新: lastUserId="+lastUserId+"  maxUserId="+user.getId());
				lastUserId = user.getId();
				check();
				return;
			}
		}
	}

	/**
	 * autocomplete
	 * 
	 * @param keyword
	 * @return
	 */
	public static Suggestion query(String keyword) {
		Suggestion suggestion = new Suggestion();
		suggestion.setQuery(keyword);

		// 返回的数据
		List<String> nicknameSuggestion = new ArrayList<String>();
		List<String> userUidData = new ArrayList<String>();

		// nickname匹配,包含该字段就可以
		for (int i = 0; i < nicknames.size(); i++) {
			String nickname = nicknames.get(i);
			if (nickname.contains(keyword)) {
				nicknameSuggestion.add(nickname);
				userUidData.add(uids.get(i));
			}
		}

		suggestion.setSuggestions(nicknameSuggestion);
		suggestion.setData(userUidData);

		return suggestion;
	}

}
